
package stcu;

import stcu.forms.*;
import stcu.control.*;
import stcu.robjects.*;
import com.nvlled.route.*;
import java.net.*;
import java.io.*;
import java.util.*;

public class Server {

    private static final String ACCOUNTS_FILENAME = "accounts";
    
    private ProbeMonitor probeMonitor;
    private ObjectRouter router;
    private ServerAuth auth;
    private Group defaultGroup;
    private String serverName;
    private Pinger pinger;

    public Server(ObjectRouter router) {
        this.router = router;
        auth = new ServerAuth(router);
        defaultGroup = new DefaultGroup(router, auth);
		serverName = UUID.randomUUID().toString();
        probeMonitor = new ProbeMonitor(serverName, router);
        GroupDemux demux = new GroupDemux(router);

        demux.register(defaultGroup);
        pinger = new Pinger(router);
        pinger.addListener(auth);
    }

    public ServerAuth getAuth() {
        return auth;
    }

    public Group getDefaultGroup() {
        return defaultGroup;
    }

    public void start() {
        new Thread(router).start();
        new Thread() { public void run() {
            try {
                router.bindBroadcast();
            } catch (Exception e) {
                javax.swing.JOptionPane.showMessageDialog(null, 
                        "Cannot bind to port. Another instance of server may already be running");
                System.exit(1);
            }
        }}.start();
        new Thread(pinger).start();
    }

   
    public void readAccounts(File file) {
        List<Account> accounts = new ArrayList<Account>();
        Scanner in = null;
        try {
            in = new Scanner(file);
        } catch (FileNotFoundException e) {
            javax.swing.JOptionPane.showMessageDialog(null, "No accounts file found.");
        }

        while (in.hasNextLine()) {
            try {
                String line = in.nextLine().trim();
				String[] fields = line.split("/");
				String idNumber = fields[0];
				String lastName = fields[1];
				String firstName = fields[2];
				Account account = new Account(idNumber,lastName,firstName);
				
                accounts.add(account);

            } catch (NoSuchElementException e) { break; }
        }
        auth.setDatabase(accounts);
    }

    public static void main(String args[]) throws Exception { 
        final ObjectRouter router = new ObjectRouter();
        Server server = new Server(router);
        ServerStart serverStart = new ControlledServerStart(server);
        serverStart.setVisible(true);
    }
}

